//
//  QTProductListViewController.m
//  qdqts
//
//  Created by jonn on 14-7-10.
//  Copyright (c) 2014年 seas.cheng. All rights reserved.
//

#import "QTProductListViewController.h"
#import "ProdListCell.h"
#import "UIImageView+UIActivityIndicatorForSDWebImage.h"
#import "QTClient.h"
#import "QTProductDetailViewController.h"
#import "MJRefresh.h"

@interface QTProductListViewController ()

@end

@implementation QTProductListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title=_pageTitle;
    _tmpArray= [[NSMutableArray alloc]init];
    
    _tableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.separatorStyle=NO;
    _failureLabel.hidden=YES;
    [_activity startAnimating];
    [self.view addSubview:_tableView];
    [self.view sendSubviewToBack:_tableView];
    [self setupRefresh];
    _num = @1;
    [self loadData];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [_tmpArray count];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *paperCell = @"ProdListCell";
    ProdListCell *cell = (ProdListCell *)[tableView dequeueReusableCellWithIdentifier:paperCell];
    
    if (cell ==nil) {
        NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"ProdListCell" owner:self options:nil];
        cell = (ProdListCell *)[nibArray objectAtIndex:0];
    }
    
    //make sure the product list 中 每一条都不是空的
    List *tempprod = (List*)[_tmpArray objectAtIndex:indexPath.row];
    if (tempprod == nil) {
        NSLog(@"no data for this product!");
        cell.ProdName.text=@"该项产品为空";
        //return 进行下一个cell
        return cell;
    }
    // 产品名称显示
    cell.ProdName.text=((List*)[_tmpArray objectAtIndex:indexPath.row]).productName;
    
    //产品质量评分
    [cell.rateView setImagesDeselected:@"startNull.png" partlySelected:@"starHalf.png" fullSelected:@"starFull.png"];
    [cell.rateView displayRating:[((List*)[_tmpArray objectAtIndex:indexPath.row]).persent floatValue]];
    
    // 产品缩略图显示
    NSURL *url=[NSURL URLWithString:[self convertPicURL:(tempprod.filePath==nil?@"":tempprod.filePath)]];
    [cell.Prodimage setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
        if (image == nil) {
            [cell.Prodimage setImage:[UIImage imageNamed:@"暂无图片.png"]];
        }
    } usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray ];
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    QTProductDetailViewController *productviewController=[[QTProductDetailViewController alloc] init];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:nil action:nil];
    self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
    [self.navigationItem setBackBarButtonItem:backItem];
    
    //传递参数到 product detail 页面
    List *tempprod = (List*)[_tmpArray objectAtIndex:indexPath.row];
    if (tempprod == nil) {
        productviewController.puid = tempprod.puid;
    }
    else
    {
        productviewController.puid = tempprod.puid==nil?@"":tempprod.puid;
    }
    
    [self.navigationController pushViewController:productviewController animated:YES];
    NSLog(@"%@",@"运行didSelectRowIndexPath");
}

#pragma mark - Table view delegate


-(NSString *)convertPicURL:(NSString *)url
{
    NSString *picURL=url;
    NSRange range_http = [url rangeOfString:@"http:"];
    NSRange range_HTTP = [url rangeOfString:@"HTTP:"];
    if ((range_http.length==0)&&(range_HTTP.length==0)) {
        picURL=[productInfoPicUrl stringByAppendingString:url==nil?@"":url];
    }
    return  picURL;
}


/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
//    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
//    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
//- (void)headerRereshing
//{
//    //重新从1加载数据
//    _num=@1;
//    [self loadData];
//}

- (void)footerRereshing
{
    //加载下一组数据
    [self loadData];
}


-(void)loadData{
    NSLog(@"当前加载数据的起始值：%@",_num);
    [[QSClient instance] loadProductList:_num
                              maxResults:@5
                             productName:self.name==nil?@"":self.name
                        manufacturerName:self.manufacturerName==nil?@"":self.manufacturerName
                             productType:self.productType==nil?@"":self.productType
                                   brand:self.brand==nil?@"":self.brand
                                keyWord:self.keyWord==nil?@"":self.keyWord
                         completionBlock:^(ProductList *productList, NSError *error){
                             NSLog(@"%@",_tmpArray);
//                             if ([_num isEqualToNumber:@1]) {
//                                 [_tmpArray removeAllObjects];
//                             }
                             [_activity stopAnimating];
                             [_tmpArray addObjectsFromArray:productList.list];
                             NSLog(@"%@",error);

                             if (error) {
//                                 _failureLabel.text=@"无法连接服务器，请检查网络";
//                                 _failureLabel.hidden=NO;
                                 UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                                               message:[NSString stringWithFormat:@"无法连接服务器，请稍后在试",nil]
                                                                           delegate:self
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil, nil];
                                 [alert show];
                             }
                             else if ([_tmpArray count]==0) {
                                 _failureLabel.text=@"没有找到您要查询的产品";
                                 _failureLabel.hidden=NO;
                             }else{
                                 _failureLabel.hidden=YES;
                                 _tableView.separatorStyle=YES;
                                 [self.tableView reloadData];
                                 _num=@(_num.intValue+5);
                             }
                             
                             //结束所有的刷新状态
                             [self.tableView headerEndRefreshing];
                             [self.tableView footerEndRefreshing];
                         }];
    
}

@end
